package com.qf.cx.simplenms.persist.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.qf.cx.simplenms.persist.dao.api.TagMemoryDao;
import com.qf.cx.simplenms.persist.entity.TagMemoryEntity;

@Repository
public class TagMemoryDaoImpl implements TagMemoryDao {
	@Autowired
	@Qualifier("hibernateSessionFactory")
	private SessionFactory sessionFactory;

	@Override
	public void addTagMemory(TagMemoryEntity tagMemory) {
		Session session = sessionFactory.getCurrentSession();
		session.save(tagMemory);
	}

	@Override
	public void deleteTagMemory(String name) {
		Session session = sessionFactory.getCurrentSession();
		TagMemoryEntity tagMemory = session.get(TagMemoryEntity.class, name);
		if (tagMemory != null) {
			session.delete(tagMemory);
		}
	}

	@Override
	public void updateTagMemory(TagMemoryEntity tagMemory) {
		Session session = sessionFactory.getCurrentSession();
		TagMemoryEntity sessionObject = session.get(TagMemoryEntity.class, tagMemory.getName());
		if (sessionObject == null) {
			session.save(tagMemory);
			return;
		}
		sessionObject.setBank(tagMemory.getBank());
		sessionObject.setLength(tagMemory.getLength());
		sessionObject.setOffset(tagMemory.getOffset());
		session.update(sessionObject);
	}

	@Override
	public TagMemoryEntity getTagMemory(String name) {
		Session session = sessionFactory.getCurrentSession();
		TagMemoryEntity tagMemory = session.get(TagMemoryEntity.class, name);
		return tagMemory;
	}

	@Override
	public List<TagMemoryEntity> getTagMemorys() {
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery("from TagMemoryEntity");
		List<TagMemoryEntity> resultList = query.list();
		return resultList;
	}

}
